<template>
  <div class="audio-guide-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <!-- 面包屑导航 -->
      <div
        class="container mx-auto px-4 py-4 border-b border-gray-200 dark:border-gray-700"
      >
        <Breadcrumb
          :items="[{ path: '/', title: '首页' }, { title: '语音导览' }]"
        />
      </div>

      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              语音导览
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              AI智能语音讲解，深入了解景点文化历史
            </p>
          </div>
          <el-button class="back-btn" @click="router.back()">
            <el-icon class="mr-1"><Back /></el-icon>
            返回上一页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧景点列表 -->
        <div class="lg:col-span-2">
          <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6">
            <!-- 搜索和筛选 -->
            <div class="space-y-4">
              <div class="flex items-center">
                <el-input
                  v-model="searchQuery"
                  placeholder="搜索景点"
                  class="w-full"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
              <div class="flex items-center justify-between overflow-x-auto pb-2">
                <el-radio-group v-model="categoryFilter" size="large">
                  <el-radio-button label="all">
                    <span class="flex items-center">
                      <el-icon class="mr-1"><Menu /></el-icon>
                      全部景点
                    </span>
                  </el-radio-button>
                  <el-radio-button 
                    v-for="cat in categories" 
                    :key="cat.id" 
                    :label="cat.id"
                    :class="{ 'hot-category': cat.isHot }"
                  >
                    <span class="flex items-center">
                      <el-icon class="mr-1" v-if="cat.isHot"><Star /></el-icon>
                      {{ cat.name }}
                    </span>
                  </el-radio-button>
                </el-radio-group>
              </div>
            </div>

            <!-- 景点列表 -->
            <div class="space-y-4">
              <el-empty v-if="filteredSpots.length === 0" description="暂无符合条件的景点" />
              <el-skeleton v-if="loading" :rows="3" animated />
              <div
                v-else
                v-for="spot in filteredSpots"
                :key="spot.id"
                class="spot-item group"
                :class="{
                  'border-2 border-primary-500 dark:border-primary-400':
                    currentSpot?.id === spot.id,
                }"
                @click="selectSpot(spot)"
              >
                <div
                  class="flex items-start p-4 rounded-xl bg-gray-50 dark:bg-gray-700/50 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors cursor-pointer"
                >
                  <el-image
                    :src="spot.cover_image"
                    class="w-32 h-32 rounded-lg object-cover flex-shrink-0 transition-transform group-hover:scale-105"
                  >
                    <template #placeholder>
                      <div class="image-placeholder">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div class="ml-4 flex-1 min-w-0">
                    <div class="flex items-start justify-between">
                      <div>
                        <h3
                          class="text-lg font-medium text-gray-900 dark:text-white mb-2"
                        >
                          {{ spot.name }}
                        </h3>
                        <p
                          class="text-gray-600 dark:text-gray-400 text-sm line-clamp-2 mb-3"
                        >
                          {{ spot.description }}
                        </p>
                      </div>
                      <el-tag
                        :type="
                          spot.category === 'historical'
                            ? 'danger'
                            : spot.category === 'natural'
                              ? 'success'
                              : 'warning'
                        "
                        size="small"
                      >
                        {{ getCategoryLabel(spot.category) }}
                      </el-tag>
                    </div>
                    <div
                      class="flex items-center text-sm text-gray-500 dark:text-gray-400 space-x-4"
                    >
                      <span class="flex items-center">
                        <el-icon class="mr-1"><Timer /></el-icon>
                        {{ spot.duration }}分钟
                      </span>
                      <span class="flex items-center">
                        <el-icon class="mr-1"><View /></el-icon>
                        {{ formatNumber(spot.playCount) }}次播放
                      </span>
                      <span class="flex items-center">
                        <el-icon class="mr-1"><Star /></el-icon>
                        {{ spot.rating.toFixed(1) }}分
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="flex justify-center mt-6">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="total"
                :page-sizes="[8, 12, 16, 24]"
                layout="total, sizes, prev, pager, next, jumper"
              />
            </div>
          </div>
        </div>

        <!-- 右侧播放器 -->
        <div class="lg:col-span-1">
          <div class="sticky top-24">
            <!-- 景点统计 -->
            <div
              class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 mb-6"
            >
              <h3 class="text-lg font-medium mb-4 flex items-center">
                <el-icon class="mr-2 text-primary-500"><DataLine /></el-icon>
                景点统计
              </h3>
              <div class="grid grid-cols-2 gap-4">
                <div
                  class="stat-card bg-primary-50 dark:bg-primary-900/20 rounded-lg p-4"
                >
                  <div
                    class="text-2xl font-bold text-primary-600 dark:text-primary-400"
                  >
                    {{ spots.length }}
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    总景点数
                  </div>
                </div>
                <div
                  class="stat-card bg-green-50 dark:bg-green-900/20 rounded-lg p-4"
                >
                  <div
                    class="text-2xl font-bold text-green-600 dark:text-green-400"
                  >
                    {{ totalPlayCount }}
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    总播放量
                  </div>
                </div>
                <div
                  class="stat-card bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4"
                >
                  <div
                    class="text-2xl font-bold text-blue-600 dark:text-blue-400"
                  >
                    {{ avgDuration }}分钟
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    平均时长
                  </div>
                </div>
                <div
                  class="stat-card bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-4"
                >
                  <div
                    class="text-2xl font-bold text-yellow-600 dark:text-yellow-400"
                  >
                    {{ avgRating }}
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    平均评分
                  </div>
                </div>
              </div>
            </div>

            <!-- 播放器 -->
            <div
              class="bg-white dark:bg-gray-800 rounded-xl shadow-md overflow-hidden mb-6"
            >
              <div v-if="currentSpot" class="relative">
                <!-- 添加关闭按钮 -->
                <el-button
                  class="absolute top-4 right-4 z-10"
                  circle
                  @click="closePlayer"
                >
                  <el-icon><Close /></el-icon>
                </el-button>
                <el-image
                  :src="currentSpot.cover_image"
                  class="w-full aspect-square object-cover"
                >
                  <template #placeholder>
                    <div class="image-placeholder aspect-square">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <!-- 渐变遮罩 -->
                <div
                  class="absolute inset-0 bg-gradient-to-t from-black/60 via-black/30 to-transparent"
                ></div>
                <!-- 播放信息 -->
                <div class="absolute bottom-0 left-0 right-0 p-6 text-white">
                  <h3 class="text-xl font-bold mb-2 drop-shadow-lg">
                    {{ currentSpot.name }}
                  </h3>
                  <p
                    class="text-sm text-gray-200 mb-4 line-clamp-2 drop-shadow"
                  >
                    {{ currentSpot.description }}
                  </p>
                  <div class="flex items-center justify-between text-sm">
                    <span class="flex items-center">
                      <el-icon class="mr-1"><Timer /></el-icon>
                      {{ formatTime(currentTime) }} /
                      {{ formatTime(totalTime) }}
                    </span>
                    <span class="flex items-center">
                      <el-icon class="mr-1"><View /></el-icon>
                      {{ formatNumber(currentSpot.playCount) }}次播放
                    </span>
                  </div>
                </div>
              </div>

              <div class="p-6">
                <template v-if="currentSpot">
                  <!-- 进度条 -->
                  <div class="mb-6">
                    <el-slider
                      v-model="playProgress"
                      :max="100"
                      class="audio-progress"
                      @change="handleProgressChange"
                    />
                  </div>

                  <!-- 控制按钮 -->
                  <div class="flex justify-center items-center space-x-6 mb-6">
                    <el-button circle class="control-btn" @click="handlePrev">
                      <el-icon><Back /></el-icon>
                    </el-button>
                    <el-button
                      circle
                      type="primary"
                      size="large"
                      class="play-btn"
                      @click="togglePlay"
                    >
                      <el-icon>
                        <component :is="isPlaying ? 'Pause' : 'VideoPlay'" />
                      </el-icon>
                    </el-button>
                    <el-button circle class="control-btn" @click="handleNext">
                      <el-icon><Right /></el-icon>
                    </el-button>
                  </div>

                  <!-- 音量控制 -->
                  <div class="flex items-center space-x-3">
                    <el-button circle class="volume-btn" @click="toggleMute">
                      <el-icon>
                        <component :is="volume === 0 ? 'Mute' : 'Microphone'" />
                      </el-icon>
                    </el-button>
                    <el-slider
                      v-model="volume"
                      :max="100"
                      class="flex-1 volume-slider"
                      @change="handleVolumeChange"
                    />
                  </div>
                </template>
                <div v-else class="text-center py-12">
                  <div
                    class="w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center mx-auto mb-4"
                  >
                    <el-icon class="text-4xl text-gray-400 dark:text-gray-500"
                      ><Microphone
                    /></el-icon>
                  </div>
                  <p class="text-gray-500 dark:text-gray-400">
                    请选择要播放的景点
                  </p>
                </div>
              </div>
            </div>

            <!-- 使用提示 -->
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6">
              <h3 class="text-lg font-medium mb-4 flex items-center">
                <el-icon class="mr-2 text-blue-500"><InfoFilled /></el-icon>
                使用提示
              </h3>
              <div class="space-y-4">
                <div class="flex items-start space-x-3">
                  <div
                    class="w-8 h-8 rounded-full bg-primary-100 dark:bg-primary-900/30 flex items-center justify-center flex-shrink-0"
                  >
                    <el-icon class="text-primary-500"><Headset /></el-icon>
                  </div>
                  <p class="text-sm text-gray-600 dark:text-gray-400">
                    建议使用耳机获得最佳听觉体验
                  </p>
                </div>
                <div class="flex items-start space-x-3">
                  <div
                    class="w-8 h-8 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center flex-shrink-0"
                  >
                    <el-icon class="text-green-500"><Download /></el-icon>
                  </div>
                  <p class="text-sm text-gray-600 dark:text-gray-400">
                    支持离线下载，无网络也可使用
                  </p>
                </div>
                <div class="flex items-start space-x-3">
                  <div
                    class="w-8 h-8 rounded-full bg-yellow-100 dark:bg-yellow-900/30 flex items-center justify-center flex-shrink-0"
                  >
                    <el-icon class="text-yellow-500"><Timer /></el-icon>
                  </div>
                  <p class="text-sm text-gray-600 dark:text-gray-400">
                    请合理安排游览时间，建议提前下载
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useRouter } from "vue-router";
import {
  Search,
  Timer,
  View,
  Back,
  Right,
  VideoPlay,
  Pause,
  Microphone,
  Picture,
  Star,
  Mute,
  DataLine,
  Headset,
  Download,
  InfoFilled,
  Close,
  Menu,
} from "@element-plus/icons-vue";
import Breadcrumb from "@/components/global/Breadcrumb.vue";
import service from "@/api/axios";

const router = useRouter();

// 语音合成相关
const speechSynthesis = window.speechSynthesis;
const speechUtterance = ref(null);
const voices = ref([]);
const selectedVoice = ref(null);

// 初始化语音合成
const initSpeechSynthesis = () => {
  // 获取可用的语音列表
  voices.value = speechSynthesis.getVoices();
  
  // 优先选择中文语音，如果没有则选择其他语音
  selectedVoice.value = voices.value.find(voice => 
    voice.lang.includes('zh') && voice.name.includes('Female')
  ) || voices.value.find(voice => 
    voice.lang.includes('zh')
  ) || voices.value[0];
  
  // 监听语音列表变化
  if (speechSynthesis.onvoiceschanged !== undefined) {
    speechSynthesis.onvoiceschanged = () => {
      voices.value = speechSynthesis.getVoices();
      selectedVoice.value = voices.value.find(voice => 
        voice.lang.includes('zh') && voice.name.includes('Female')
      ) || voices.value.find(voice => 
        voice.lang.includes('zh')
      ) || voices.value[0];
    };
  }
};

// 播放语音
const playSpeech = (text, name) => {
  if (!text) {
    return;
  }
  
  // 检查语音合成API是否可用
  if (!speechSynthesis) {
    return;
  }
  
  // 停止当前播放
  stopSpeech();
  
  // 创建新的语音实例
  speechUtterance.value = new SpeechSynthesisUtterance();
  
  // 确认语音选择是否有效
  if (!selectedVoice.value) {
    // 重新获取可用语音
    const availableVoices = speechSynthesis.getVoices();
    selectedVoice.value = availableVoices.find(voice => 
      voice.lang.includes('zh')
    ) || availableVoices[0];
  }
  
  speechUtterance.value.voice = selectedVoice.value;
  speechUtterance.value.rate = 0.9;
  speechUtterance.value.pitch = 1.1;
  speechUtterance.value.volume = volume.value / 100;
  speechUtterance.value.lang = 'zh-CN'; // 确保使用中文
  
  // 添加标点符号停顿
  const addPauses = (text) => {
    return text
      .replace(/。/g, '。\n')
      .replace(/！/g, '！\n')
      .replace(/？/g, '？\n')
      .replace(/，/g, '，\n')
      .replace(/；/g, '；\n')
      .replace(/：/g, '：\n');
  };
  
  // 设置完整文本（景点名称 + 描述）
  const fullText = `${name}。\n${addPauses(text)}`;
  speechUtterance.value.text = fullText;
  
  // 监听语音播放错误事件
  speechUtterance.value.onerror = (event) => {
    isPlaying.value = false;
  };
  
  // 监听语音播放结束
  speechUtterance.value.onend = () => {
    isPlaying.value = false;
    playProgress.value = 0;
    currentTime.value = 0;
  };
  
  // 监听语音播放进度
  speechUtterance.value.onboundary = (event) => {
    if (event.name === 'word') {
      const progress = (event.charIndex / fullText.length) * 100;
      playProgress.value = progress;
      currentTime.value = (progress / 100) * totalTime.value;
    }
  };
  
  // 开始播放
  try {
    speechSynthesis.speak(speechUtterance.value);
    isPlaying.value = true;
  } catch (error) {
    isPlaying.value = false;
  }
};

// 停止语音播放
const stopSpeech = () => {
  if (speechSynthesis.speaking) {
    speechSynthesis.cancel();
  }
  isPlaying.value = false;
  playProgress.value = 0;
  currentTime.value = 0;
};

// 暂停语音播放
const pauseSpeech = () => {
  if (speechSynthesis.speaking) {
    speechSynthesis.pause();
  }
  isPlaying.value = false;
};

// 恢复语音播放
const resumeSpeech = () => {
  if (speechSynthesis.paused) {
    speechSynthesis.resume();
  }
  isPlaying.value = true;
};

// 设置语音参数
const setVoiceSettings = (settings = {}) => {
  if (speechUtterance.value) {
    const {
      rate = 0.9,
      pitch = 1.1,
      volume = volume.value / 100
    } = settings;
    
    speechUtterance.value.rate = rate;
    speechUtterance.value.pitch = pitch;
    speechUtterance.value.volume = volume;
  }
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(0);
const loading = ref(false);

// 筛选相关
const searchQuery = ref("");
const categoryFilter = ref("all");

// 获取分类标签
const getCategoryLabel = (category) => {
  // 确保categories.value是数组
  if (!Array.isArray(categories.value)) {
    // 使用默认值
    const labels = {
      historical: "历史遗迹",
      natural: "自然景观",
      popular: "热门景点",
      culture: "人文景观",
      temple: "寺庙祠堂",
      museum: "博物馆",
      water: "水域",
      mountain: "山地",
      forest: "森林",
    };
    return labels[category] || "其他";
  }
  
  // 从分类列表中查找对应的名称
  const foundCategory = categories.value.find(cat => cat.code?.toLowerCase() === category);
  if (foundCategory) {
    return foundCategory.name;
  }
  
  // 如果找不到分类，使用默认值
  const labels = {
    historical: "历史遗迹",
    natural: "自然景观",
    popular: "热门景点",
    culture: "人文景观",
    temple: "寺庙祠堂",
    museum: "博物馆",
    water: "水域",
    mountain: "山地",
    forest: "森林",
  };
  return labels[category] || "其他";
};

// 景点数据
const spots = ref([]);
const categories = ref([]);

// 测试数据，当接口请求失败时使用
const testSpots = [
  {
    id: 1,
    name: "贵港博物馆",
    description:
      "了解贵港历史文化的重要窗口，展示了贵港从古至今的发展历程，包含大量珍贵文物展品。",
    cover_image: "/static/images/spots/museum.jpg",
    duration: 15,
    playCount: 12345,
    rating: 4.8,
    category: "historical",
    audio_url: "/static/audio/museum.mp3",
  },
  {
    id: 2,
    name: "江滨公园",
    description:
      "贵港标志性的滨江景观带，是市民休闲娱乐的好去处，沿江绿道景色优美。",
    cover_image: "/static/images/spots/riverside.jpg",
    duration: 10,
    playCount: 23456,
    rating: 4.6,
    category: "natural",
    audio_url: "/static/audio/riverside.mp3",
  },
  {
    id: 3,
    name: "荷城古镇",
    description:
      "千年古镇，保留了大量明清时期的建筑，展现了贵港的历史风貌和传统文化。",
    cover_image: "/static/images/spots/ancient-town.jpg",
    duration: 20,
    playCount: 34567,
    rating: 4.9,
    category: "historical",
    audio_url: "/static/audio/ancient-town.mp3",
  },
];

// 加载分类数据
const loadCategories = async () => {
  try {
    // 使用公开接口，不需要认证
    const res = await service.get('/public/spot/categories');
    // 处理返回的数据格式
    const categoriesData = res.data || res;
    
    // 确保categories是数组
    if (Array.isArray(categoriesData)) {
      categories.value = categoriesData;
      
      // 如果有热门分类，添加到前面
      const hotCategories = categoriesData.filter(cat => cat.is_hot);
      if (hotCategories.length > 0) {
        // 添加热门分类标记，前端可以特殊处理
        hotCategories.forEach(cat => cat.isHot = true);
      }
    } else {
      throw new Error('分类数据格式不正确');
    }
  } catch (error) {
    // 使用测试分类数据
    categories.value = [
      { id: 'historical', name: '历史遗迹', code: 'HISTORICAL' },
      { id: 'natural', name: '自然景观', code: 'NATURE' },
      { id: 'culture', name: '人文景观', code: 'CULTURE' },
      { id: 'water', name: '水域', code: 'WATER' },
      { id: 'mountain', name: '山地', code: 'MOUNTAIN' },
      { id: 'temple', name: '寺庙祠堂', code: 'TEMPLE' },
      { id: 'museum', name: '博物馆', code: 'MUSEUM' }
    ];
  }
};

// 加载景点数据
const loadSpots = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchQuery.value,
      category: categoryFilter.value !== 'all' ? categoryFilter.value : null
    };
    
    // 使用公开接口，不需要认证
    const res = await service.get('/public/spot/list', { params });
    
    // 处理返回的数据格式
    const spotsData = res.data || res;
    
    // 处理返回的数据
    if (spotsData && (spotsData.content || Array.isArray(spotsData))) {
      // 判断是分页格式还是直接数组
      const spotList = spotsData.content || spotsData;
      
      if (Array.isArray(spotList)) {
        spots.value = spotList.map(spot => ({
          ...spot,
          // 字段名适配 (兼容驼峰和下划线命名)
          coverImage: spot.coverImage || spot.cover_image,
          cover_image: (spot.coverImage || spot.cover_image || '').replace('/images/', '/static/images/') || `/static/images/spots/default.jpg`,
          // 在前端模拟生成这些属性
          playCount: Math.floor(Math.random() * 50000 + 5000),
          duration: Math.floor(Math.random() * 20 + 5),
          rating: parseFloat((Math.random() * 1 + 4).toFixed(1)) // 生成4.0-5.0之间的评分
        }));
        total.value = spotsData.totalElements || spotList.length;
      } else {
        throw new Error('数据不是数组格式');
      }
    } else {
      throw new Error('数据格式不正确');
    }
  } catch (error) {
    // 使用测试数据
    spots.value = testSpots.map(spot => ({
      ...spot,
      // 确保图片路径正确
      coverImage: spot.cover_image.replace('/static/images/', '/images/'),
      cover_image: spot.cover_image
    }));
    total.value = testSpots.length;
  } finally {
    loading.value = false;
  }
};

// 获取景点详情的后备方案
const getSpotDetailFallback = (id) => {
  // 首先尝试从当前列表中找到对应景点
  const existingSpot = spots.value.find(s => s.id === parseInt(id));
  
  if (existingSpot) {
    // 如果没有音频导览数据，添加默认数据
    if (!existingSpot.audioGuide) {
      existingSpot.audioGuide = {
        guideText: existingSpot.description,
        duration: 300,
        language: "zh_CN"
      };
    }
    
    return existingSpot;
  }
  
  // 如果找不到，返回默认数据
  return {
    id: parseInt(id),
    name: "贵港景点",
    category: "others",
    coverImage: "/static/images/spots/default.jpg",
    cover_image: "/static/images/spots/default.jpg",
    description: "这是一个美丽的贵港景点，详细信息暂时无法获取。",
    playCount: Math.floor(Math.random() * 30000) + 5000,
    rating: (Math.random() * 2 + 3).toFixed(1),
    duration: 10,
    audioGuide: {
      guideText: "这是一个美丽的贵港景点，详细信息暂时无法获取。您可以稍后再试，或联系景区管理员了解更多信息。",
      duration: 300,
      language: "zh_CN"
    }
  };
};

// 获取景点详情
const getSpotDetail = async (id) => {
  try {
    const response = await service.get(`/public/spot/${id}`);
    
    // 处理返回数据 - 兼容两种可能的数据格式
    let spotDetail;
    if (response.data && response.data.code === 200) {
      // 标准API格式: {code: 200, message: 'xxx', data: {...}}
      spotDetail = response.data.data;
    } else {
      // 直接返回数据对象格式
      spotDetail = response.data || response;
    }
    
    // 确保audioGuide对象存在
    if (!spotDetail.audioGuide && spotDetail.audio_guide) {
      spotDetail.audioGuide = spotDetail.audio_guide;
    }
    
    // 特别检查解说词数据
    if (spotDetail.audioGuide) {
      // 确保guideText正确映射
      if (!spotDetail.audioGuide.guideText && spotDetail.audioGuide.guide_text) {
        spotDetail.audioGuide.guideText = spotDetail.audioGuide.guide_text;
      }
    }
    
    // 处理图片路径问题 - 确保图片路径正确
    if (spotDetail.coverImage && !spotDetail.coverImage.startsWith('/static')) {
      // 如果图片路径不包含/static前缀，则添加
      spotDetail.cover_image = `/static${spotDetail.coverImage}`;
    } else if (spotDetail.coverImage) {
      // 如果已有正确路径，直接复制
      spotDetail.cover_image = spotDetail.coverImage;
    }
    
    // 添加默认值（如果后端没有返回相应字段）
    const processedSpot = {
      ...spotDetail,
      playCount: spotDetail.playCount || Math.floor(Math.random() * 50000) + 10000,
      rating: spotDetail.rating || (Math.random() * 2 + 3).toFixed(1),
      duration: spotDetail.duration || (spotDetail.audioGuide?.duration ? Math.ceil(spotDetail.audioGuide.duration / 60) : 15),
    };
    
    return processedSpot;
  } catch (error) {
    // 使用后备方案获取详情
    return getSpotDetailFallback(id);
  }
};

// 增加播放次数
const increasePlayCount = async (spotId) => {
  try {
    // 使用公开接口，不需要认证
    await service.post(`/public/spot/${spotId}/increase-play-count`);
  } catch (error) {
    // 在前端模拟增加播放次数
    const spot = spots.value.find(s => s.id === spotId);
    if (spot) {
      spot.playCount += 1;
    }
  }
};

// 监听筛选条件变化
watch([searchQuery, categoryFilter], () => {
  currentPage.value = 1; // 重置页码
  loadSpots();
});

// 监听分页变化
watch([currentPage, pageSize], () => {
  loadSpots();
});

// 过滤景点
const filteredSpots = computed(() => spots.value);

// 播放控制相关
const currentSpot = ref(null);
const isPlaying = ref(false);
const playProgress = ref(0);
const currentTime = ref(0);
const totalTime = ref(0);
const volume = ref(80);
let audioTimer = null;

// 修改选择景点函数
const selectSpot = async (spot) => {
  if (currentSpot.value?.id === spot.id) return;
  
  // 停止当前播放
  stopSpeech();
  
  // 显示加载中状态
  loading.value = true;
  
  try {
    // 直接使用getSpotDetail获取详细数据
    const detailedSpot = await getSpotDetail(spot.id);
    
    if (detailedSpot) {
      currentSpot.value = detailedSpot;
    } else {
      currentSpot.value = spot;
    }
  } catch (error) {
    currentSpot.value = spot;
  } finally {
    loading.value = false;
  }
  
  // 重置播放状态
  isPlaying.value = false;
  playProgress.value = 0;
  currentTime.value = 0;
  totalTime.value = currentSpot.value.duration * 60;
};

// 修改播放控制函数
const togglePlay = () => {
  if (!currentSpot.value) return;
  
  if (isPlaying.value) {
    pauseSpeech();
  } else {
    if (speechSynthesis.paused) {
      resumeSpeech();
    } else {
      // 增加播放计数
      increasePlayCount(currentSpot.value.id);
      
      // 获取朗读内容 - 强制使用解说词
      let textToRead = '';
      
      // 检查audioGuide对象路径是否存在
      if (currentSpot.value.audioGuide && currentSpot.value.audioGuide.guideText) {
        // 优先使用 audioGuide.guideText (驼峰命名)
        textToRead = currentSpot.value.audioGuide.guideText;
      } else if (currentSpot.value.audioGuide && currentSpot.value.audioGuide.guide_text) {
        // 兼容 audioGuide.guide_text (下划线命名)
        textToRead = currentSpot.value.audioGuide.guide_text;
      } else if (currentSpot.value.audio_guide && currentSpot.value.audio_guide.guide_text) {
        // 兼容 audio_guide.guide_text (全下划线命名)
        textToRead = currentSpot.value.audio_guide.guide_text;
      } else {
        // 无解说词数据，尝试重新获取景点信息
        getSpotDetail(currentSpot.value.id).then(updatedSpot => {
          if (updatedSpot && updatedSpot.audioGuide && updatedSpot.audioGuide.guideText) {
            playSpeech(updatedSpot.audioGuide.guideText, updatedSpot.name);
          } else {
            playSpeech(currentSpot.value.description, currentSpot.value.name);
          }
        });
        return; // 等待异步获取结果后再朗读
      }
      
      // 确保有内容才进行朗读
      if (textToRead && textToRead.trim()) {
        // 播放语音
        playSpeech(textToRead, currentSpot.value.name);
      } else {
        // 使用描述作为备选
        playSpeech(currentSpot.value.description, currentSpot.value.name);
      }
    }
  }
};

// 修改音量控制函数
const handleVolumeChange = (value) => {
  if (speechUtterance.value) {
    speechUtterance.value.volume = value / 100;
    // 如果正在播放，重新应用设置
    if (speechSynthesis.speaking) {
      speechSynthesis.cancel();
      speechSynthesis.speak(speechUtterance.value);
    }
  }
};

// 修改关闭播放器函数
const closePlayer = () => {
  stopSpeech();
  currentSpot.value = null;
  isPlaying.value = false;
  playProgress.value = 0;
  currentTime.value = 0;
  totalTime.value = 0;
};

// 在组件挂载时初始化
onMounted(() => {
  initSpeechSynthesis();
  loadCategories();
  loadSpots();
});

// 在组件卸载时停止语音播放
onUnmounted(() => {
  stopSpeech();
});

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);
  return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
};

// 计算统计数据
const totalPlayCount = computed(() => {
  return spots.value.reduce((sum, spot) => sum + (spot.playCount || 0), 0);
});

const avgDuration = computed(() => {
  const total = spots.value.reduce((sum, spot) => sum + (spot.duration || 0), 0);
  return Math.round(total / (spots.value.length || 1));
});

const avgRating = computed(() => {
  const total = spots.value.reduce((sum, spot) => sum + (spot.rating || 0), 0);
  return (total / (spots.value.length || 1)).toFixed(1);
});

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

const handlePrev = () => {
  const currentIndex = spots.value.findIndex(
    (s) => s.id === currentSpot.value?.id,
  );
  if (currentIndex > 0) {
    selectSpot(spots.value[currentIndex - 1]);
  }
};

const handleNext = () => {
  const currentIndex = spots.value.findIndex(
    (s) => s.id === currentSpot.value?.id,
  );
  if (currentIndex < spots.value.length - 1) {
    selectSpot(spots.value[currentIndex + 1]);
  }
};

const handleProgressChange = (value) => {
  if (!currentSpot.value) return;
  currentTime.value = (value / 100) * totalTime.value;
};

const toggleMute = () => {
  volume.value = volume.value === 0 ? 80 : 0;
};
</script>

<style lang="scss" scoped>
.audio-guide-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .page-header {
    @apply mb-6;
  }

  .spot-item {
    @apply rounded-xl transition-all duration-300;

    &:hover {
      @apply shadow-md transform -translate-y-1;
    }
  }

  .image-placeholder {
    @apply w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-700;

    .el-icon {
      @apply text-3xl text-gray-400 dark:text-gray-500;
    }
  }

  :deep(.el-slider) {
    &.audio-progress {
      .el-slider__runway {
        @apply bg-gray-200 dark:bg-gray-600;
      }

      .el-slider__bar {
        @apply bg-primary-500 dark:bg-primary-400;
      }

      .el-slider__button {
        @apply border-primary-500 dark:border-primary-400;
      }
    }

    &.volume-slider {
      .el-slider__runway {
        @apply bg-gray-200 dark:bg-gray-600;
      }

      .el-slider__bar {
        @apply bg-gray-400 dark:bg-gray-500;
      }

      .el-slider__button {
        @apply border-gray-400 dark:border-gray-500;
      }
    }
  }

  :deep(.el-radio-button__inner) {
    @apply dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600;

    &:hover {
      @apply dark:bg-gray-600;
    }
  }

  :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
    @apply dark:bg-primary-600 dark:text-white dark:border-primary-600;
  }

  :deep(.hot-category .el-radio-button__inner) {
    @apply text-amber-500 font-bold;
    
    .el-icon {
      @apply text-amber-500;
    }
  }

  :deep(.el-input__wrapper) {
    @apply dark:bg-gray-700 dark:border-gray-600;

    input {
      @apply dark:text-gray-300;

      &::placeholder {
        @apply dark:text-gray-500;
      }
    }
  }

  :deep(.el-tag) {
    &.el-tag--success {
      @apply dark:bg-green-900/60 dark:text-green-300 dark:border-green-700;
    }
    &.el-tag--danger {
      @apply dark:bg-red-900/60 dark:text-red-300 dark:border-red-700;
    }
    &.el-tag--warning {
      @apply dark:bg-yellow-900/60 dark:text-yellow-300 dark:border-yellow-700;
    }
  }

  :deep(.el-pagination) {
    @apply dark:bg-transparent;

    .el-pagination__total {
      @apply dark:text-gray-400;
    }

    .btn-prev,
    .btn-next {
      @apply dark:bg-gray-700 dark:text-gray-300;
    }

    .el-pager li {
      @apply dark:bg-gray-700 dark:text-gray-300;

      &.active {
        @apply dark:bg-primary-600 dark:text-white;
      }
    }
  }

  .control-btn {
    @apply hover:bg-gray-100 dark:hover:bg-gray-700;
  }

  .play-btn {
    @apply w-14 h-14 text-xl;
  }

  .volume-btn {
    @apply hover:bg-gray-100 dark:hover:bg-gray-700;
  }
}
</style>
